/*
 * DB access manager
 *
 * License: LGPL v3
 */
package org.passwordstore.util;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.passwordstore.Resource;

/**
 *
 * @author thotheolh
 */
public class DBManager {

    private String connPath = null;
    private String username = null;
    private String password = null;

    public DBManager(String connPath, String username, String password) {
        this.setConnPath(processConnPath(connPath));
        this.setUsername(username);
        this.setPassword(password);
    }

    /**
     * Get database connection
     * @return SQL Connection
     */
    public Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("org.h2.Driver").newInstance();
            connection = DriverManager.getConnection(getConnPath(), getUsername(), getPassword());
        } catch (SQLException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }

    /**
     * @return the connPath
     */
    public String getConnPath() {
        return connPath;
    }

    /**
     * @param connPath the connPath to set
     */
    public void setConnPath(String connPath) {
        this.connPath = connPath;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Process Connection Paths to identify JDBC or LocalDB urls and convert them
     * to JDBC urls.jdbc:h2:file: - jdbc h2 format. local:/DBStore/Password - localdb format
     * @param jdbcUrl
     * @return
     */
    public String processConnPath(String jdbcUrl) {
        return Resource.getInstance().processConnPath(jdbcUrl);
    }
}
